//
//  HomeTableViewController.swift
//  demo01新浪微博
//
//  Created by 杨兵 on 15/5/10.
//  Copyright (c) 2015年 bing. All rights reserved.
//

import UIKit


class HomeTableViewController: BaseTableViewController, StatusCellDelegate, PopoverAnimationPopoverAnimationDelegate {

    @IBOutlet weak var titlebtn: HomeButton!
    
    var heigthCache: NSCache = NSCache()
    
    // 上拉刷新标志
    var isPullRefresh = false
    
    // 数据源,set值后重新加载
    var statuses:[Status]? {
        didSet {
            self.tableView.reloadData()
        }
    }

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置 popover 转场代理
        popanimationDelegate.delegate = self
        
        setupRefreshControl()
    }
    
    
    func setupRefreshControl() {
        // 设置刷新
        self.refreshControl = HomeRefreshControl()
        self.refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        loadData()
    }
    
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        setNav()
    }
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        visitorLoginView?.setupInfo("visitordiscover_feed_image_house", msg: "关注一些人，回这里看看有什么惊喜", isHome:true)
    }
    
    
    // 设置标题栏
    func setNav() {
        if isLogin {
            titlebtn.setTitle(userInfoShared?.name, forState: UIControlState.Normal)
        } else {
            titlebtn.setImage(nil, forState: UIControlState.Highlighted)
            titlebtn.setImage(nil, forState: UIControlState.Normal)
        }
    }
    
    
    // MARK: - 加载数据
    func loadData() {
        refreshControl?.beginRefreshing()
        
        // 默认下拉刷新
        var maxId = 0
        var sinceId = statuses?.first?.id ?? 0
        
        // 如果是上拉刷新
        if isPullRefresh {
            sinceId = 0
            maxId = statuses?.last?.id ?? 0
        }
        
        Status.loadStatus(since_Id:sinceId, max_id: maxId, complete: { (mystatuses) -> () in
            self.refreshControl?.endRefreshing()
            
            // 数据
            if mystatuses == nil {
                println("没有数据")
                return
            }
            
            if sinceId > 0 {
                
                // 上拉刷新,将数据加到最前
                self.statuses! = mystatuses! + self.statuses!
            } else if maxId > 0 && self.isPullRefresh {
                
                // 将数据加载到最后
                self.statuses! += mystatuses!
                self.isPullRefresh = false
            } else {
                
                // 首次刷新
                self.statuses = mystatuses
            }
            
        })
        
    }
    
    
    // MARK: - UITableViewDataSource数据源
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let status = statuses![indexPath.row]
        var cell = tableView.dequeueReusableCellWithIdentifier(StatusCell.cellType(status)) as! StatusCell
        cell.photoDelegate = self
        cell.status = status
        
        // 划到最后一条的时候默认加载数据
        if !isPullRefresh && indexPath.row == statuses!.count - 1 {
            isPullRefresh = true
            loadData()
        }
        return cell
    }
    
    
    // 预估行高
    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 300
    }
    
    
    // 准确行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = statuses![indexPath.row]
        
        // 缓存获取行高
        var height: AnyObject? = heigthCache.objectForKey(status.id)
        if height != nil {
            return CGFloat(height!.floatValue)
        }
        var cell = tableView.dequeueReusableCellWithIdentifier(StatusCell.cellType(status)) as! StatusCell
        let heightrow = cell.getRowHeight(status)
        heigthCache.setObject(heightrow, forKey: status.id)
        return heightrow
    }

    
    //MARK: -  popover下拉框转场 代理
    let popanimationDelegate = PopoverAnimationDelegate()
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "HomeToPopover" {
            let desview = segue.destinationViewController as! PopoverViewController
            
            // 设置modall模型
            desview.modalPresentationStyle = UIModalPresentationStyle.Custom
            
            // 设置转场代理
            desview.transitioningDelegate = popanimationDelegate;
        }
    }
    
    
    // PopoverAnimationPopoverAnimationDelegate代理,用于修改pop箭头上下切换
    func isPresented(isPopOver: Bool) {
        titlebtn.selected = isPopOver
    }
    
    
    //MARK: -  跳转到二维码页面
    @IBAction func HomeToQRcodepage(sender: AnyObject) {
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        let nav = sb.instantiateInitialViewController() as! UINavigationController
        presentViewController(nav, animated: true, completion: nil)
    }
    

    // MARK: - 图片浏览器转场 代理
    let photoanimation = PhotoViewAnimation()
    func didSelectedPhotoIndex(cell: StatusCell, index: Int) {
        let PhotoVC = PhotoViewController()
        PhotoVC.selectedIndex = index
        PhotoVC.imageUrls = cell.status?.largePicture
        
        // 设置转场代理
        PhotoVC.transitioningDelegate = photoanimation
        PhotoVC.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(PhotoVC, animated: true, completion: nil)
    }
    
}



